package com.easylinkin.linkappapi.lobar.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.async.AsyncUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.lobar.dto.GateQueryDTO;
import com.easylinkin.linkappapi.lobar.dto.UserProjectDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDTO;
import com.easylinkin.linkappapi.lobar.entity.Gate;
import com.easylinkin.linkappapi.lobar.entity.UserGateLink;
import com.easylinkin.linkappapi.lobar.entity.UserProject;
import com.easylinkin.linkappapi.lobar.service.GateService;
import com.easylinkin.linkappapi.lobar.vo.GateRecordVo;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import jodd.util.StringUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 项目闸机管理
 */
@RestController
@RequestMapping("gate")
@Api(tags = "项目闸机管理")
public class GateController {

  @Autowired
  private GateService gateService;
  @Autowired
  private RedisTemplate redisTemplate;
  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  /**
   * @Description: 增加闸机
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加闸机")
  public RestMessage insert(@RequestBody Gate gate){
    // 参数验证
    checkParams(gate);
    gateService.insert(gate);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除闸机关联人员
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping("link")
  @ApiOperation("删除闸机关联人员")
  public RestMessage deleteLink(@RequestBody UserGateLink userGateLink){
    Assert.notEmpty(userGateLink.getIds(),"id不能为空");
    gateService.deleteLink(userGateLink.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 增加闸机授权人员
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("user")
  @ApiOperation("增加闸机")
  public RestMessage insertUser(@RequestBody Gate gate){
    gateService.insertUser(gate);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 解除绑定
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping("user")
  @ApiOperation("解除绑定")
  public RestMessage delUser(@RequestBody Gate gate){
    Assert.notEmpty(gate.getIds(),"id不能为空");
    gateService.delUser(gate.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除闸机（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping
  @ApiOperation("删除闸机（包含批量删除）")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "")
  public RestMessage delBatch(@RequestBody Gate gate){
    Assert.notEmpty(gate.getIds(),"id不能为空");
    //记录日志
    Set<String> ids = gate.getIds();
    if(CollectionUtil.isNotEmpty(ids)){
      QueryWrapper<Gate> qw = new QueryWrapper<>();
      qw.in("id",ids);
      List<Gate> ls = gateService.list(qw);
      if(CollectionUtil.isNotEmpty(ls)){
        List<String> gateNames = new ArrayList<>();
        ls.stream().forEach(l -> {
          gateNames.add(l.getName());
        });
        LogHelper.setContent(LogConstant.LogOperateType.LABOL_GATE_DELETE, StringUtil.join(gateNames,","));
      }
    }
    gateService.delBatch(gate.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑闸机
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑闸机")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "")
  public RestMessage updateById(@RequestBody Gate gate){
    Assert.notNull(gate.getId(),"id不能为空");
    //记录日志
    Gate dbGate = gateService.getById(gate.getId());
    if(dbGate != null){
      LogHelper.setContent(LogConstant.LogOperateType.LABOL_GATE_EDIT, dbGate.getName());
    }
    gateService.updateOne(gate);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询闸机详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询闸机详情")
  public RestMessage findById(@PathVariable("id")String id) {
    Assert.notNull(id,"id不能为空");
    Gate gate = gateService.getById(id);
    return RestBuilders.successBuilder().data(gate).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<Gate> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<Gate> record =  gateService.queryListByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("user/list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryUserByPage(@RequestBody RequestModel<UserProject> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<UserProjectDTO> record =  gateService.queryUserByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * 同步授权人员
   * @param gate
   */
  @PostMapping("upUserToGate")
  @ApiOperation("同步授权人员")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "")
  public RestMessage upUserToGate(@RequestBody Gate gate){
    Assert.notNull(gate.getId(),"id不能为空");
    //记录日志
    Gate dbGate = gateService.getById(gate.getId());
    if(dbGate != null){
      LogHelper.setContent(LogConstant.LogOperateType.LABOL_UP_USER_TO_GATE, dbGate.getName());
    }
//    //获取当前时间的时间
//    Calendar calendar = Calendar.getInstance();
//    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
//    String key = "userProjectReal:"+formatter.format(calendar.getTime());
    gateService.upUserToGate(gate.getId());
//    AsyncUtil.submitTask(key,() ->{
//      ExcelResultDTO resultDTO;
//      try {
//        resultDTO = gateService.upUserToGate(gate.getId());
//      } catch (Exception e) {
//        throw new BusinessException(e.getMessage());
//      }
//      return resultDTO;
//    });
    return RestBuilders.successBuilder().build();
  }

  /**
   * 查询下发闸机结果
   * @param id
   */
  @GetMapping("result")
  @ApiOperation("查询下发闸机结果")
  public RestMessage getResult(String id){
    Assert.notNull(id,"id不能为空");
    Object o = redisTemplate.opsForValue().get(Gate.getRedisIdPre() + id);
    return RestBuilders.successBuilder().data(o).build();
  }

  /**
   * 查询可选择的下拉闸机设备选项
   * @param code  编辑时带上自身数据设备code
   */
  @GetMapping("device")
  @ApiOperation("查询可选择的下拉闸机设备选项")
  public RestMessage getDeviceList(String code){
    List<Device> deviceList = gateService.getDeviceList(code);
    return RestBuilders.successBuilder().data(deviceList).build();
  }

  @PostMapping("/selectGateRecords")
  @ApiOperation("闸机记录查询")
  public RestMessage selectGateRecords(@RequestBody RequestModel<GateQueryDTO> requestModel) {
    Assert.notNull(requestModel.getCustomQueryParams(),  "查询条件不能为空");
    Assert.notNull(requestModel.getPage(), "分页参数不能为空");
    IPage<GateRecordVo> gateRecordVoIPage = gateService.selectGateRecords(requestModel);
    return RestBuilders.successBuilder().data(gateRecordVoIPage).build();
  }

  @PostMapping("/getAllGates")
  @ApiOperation("获取项目所有的闸机")
  public RestMessage getAllGates() {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    QueryWrapper<Gate> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("tenant_id_", tenantId).orderByDesc("modify_time_");
    List<Gate> gates = gateService.list(queryWrapper);
    return RestBuilders.successBuilder().data(gates).build();
  }

  private void checkParams(Gate gate){
    Assert.notNull(gate, "gate 不能为空");
    Assert.notNull(gate.getName(), "闸机名称 不能为空");
    Assert.notNull(gate.getCode(), "序列号 不能为空");
//    Assert.notNull(gate.getBrand(), "品牌号 不能为空");
    Assert.notNull(gate.getDirection(), "方向 不能为空");
    // 绑定工地卫士 校验字段
    if(Integer.valueOf(1).equals(gate.getBladeGuardBindStatus())){
      Assert.notNull(gate.getBladeGuardUserId(), "userID 不能为空");
      Assert.notNull(gate.getBladeGuardProjectId(), "projectID 不能为空");
      Assert.notNull(gate.getBladeGuardJingDu(), "闸机经度 不能为空");
      Assert.notNull(gate.getBladeGuardWeiDu(), "闸机纬度 不能为空");
      Assert.notNull(gate.getBladeGuardProjectName(), "项目名称 不能为空");
      Assert.notNull(gate.getBladeGuardProjectAddress(), "项目地址 不能为空");
    }
  }
}

